//
//  BNDOfficeDocPDFView.m
//  OfficeDoc
//
//  Created by pie on 2022/4/3.
//  Copyright © 2022 pie. All rights reserved.
//

#import "BNDOfficeDocPDFView.h"
#import "LVUIUtils.h"
#import "BNDOfficeDocDetailsWebVc.h"
#import "LVDownLoadManager.h"
#import <WebKit/WebKit.h>
#import "ReminderHUD.h"

@interface BNDOfficeDocPDFView ()<WKNavigationDelegate,WKUIDelegate, UIScrollViewDelegate,UIDocumentInteractionControllerDelegate>
@property (strong, nonatomic) UIImageView *iconImageView;
@property (strong, nonatomic) UIView *topView;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIButton *downloadBtn;
@property (strong, nonatomic) UIButton *previewBtn;
@property (strong, nonatomic) WKWebView  *webView;
@property (assign, nonatomic) BOOL isComplete; //是否完成

@property (weak, nonatomic)  NSString *urlString; //链接

@property (strong, nonatomic)  LVDownLoadManager *downLoadManager; //链接
@property (strong, nonatomic) UIDocumentInteractionController * documentController;

@end

@implementation BNDOfficeDocPDFView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = UIColor.redColor;
        self.layer.borderColor = UIColorWithHex(0xE1E4EB).CGColor;
        self.layer.borderWidth = 0.5;
        self.layer.cornerRadius = 3;
        self.layer.masksToBounds = YES;
        
        _topView = [[UIView alloc] init];
        _topView.backgroundColor = UIColor.whiteColor;
        [self addSubview:_topView];
        [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.mas_equalTo(self);
            make.height.mas_equalTo(44);
        }];
        
        [LVUIUtils addLineInView:_topView top:NO leftMargin:0 rightMargin:0];
        
        _iconImageView = [[UIImageView alloc] initWithImage:BNDImageNamed(@"bnd_icon_pdf")];
        [_topView addSubview:_iconImageView];
        [_iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left).offset(12);
            make.centerY.mas_equalTo(self.topView);
            make.size.mas_equalTo(CGSizeMake(20, 20));
        }];
        
        _titleLabel = ({
            UILabel *titleLabel = [[UILabel alloc] init];
            titleLabel.font = BNDPFRegularFont(14);
            titleLabel.textColor = UIColorWithHex(0x51555D);
            titleLabel.text = @"关于2022年春节放假安排的通知";
            titleLabel.numberOfLines = 1;
            titleLabel;
        });
        [self addSubview:_titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.iconImageView.mas_right).offset(6);
            make.right.mas_equalTo(self.topView.mas_right).offset(-16);
            make.centerY.mas_equalTo(self.iconImageView);
        }];
        
        
        _previewBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_previewBtn lk_setImage:BNDImageNamed(@"bnd_yulan")];
        [self addSubview:_previewBtn];
        [_previewBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.mas_right).offset(-12);
            make.centerY.mas_equalTo(self.topView);
            make.size.mas_equalTo(CGSizeMake(20, 20));
        }];
        
        _downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_downloadBtn lk_setImage:BNDImageNamed(@"bnd_xiazai")];
        [self addSubview:_downloadBtn];
        [_downloadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.previewBtn.mas_left).offset(-10);
            make.centerY.mas_equalTo(self.topView);
            make.size.mas_equalTo(CGSizeMake(20, 20));
        }];
        
        [self addSubview:self.webView];
        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(self);
            make.top.mas_equalTo(self.topView.mas_bottom);
        }];

        
       @weakify(self)
        [[_previewBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [BNDPushVCHandler pushWenVc:[[BNDPreference sharedInstance] handleProduceImageUrl:self.infoData[@"pdfUrl"]] withDownload:self.model.docDownload name:self.infoData[@"fileName"]];
        }];
        
        [[_downloadBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            [self handleDownLoadManager];
        }];
    }
    
    return self;
}

- (void)setInfoData:(NSDictionary *)infoData
{
    _infoData = infoData;
    _titleLabel.text = infoData[@"fileName"];
    [self loadDataMethod:[[BNDPreference sharedInstance] handleProduceImageUrl:infoData[@"pdfUrl"]]];
    self.downloadBtn.hidden = !self.model.docDownload;
    
}

- (void)handleDownLoadManager
{

    _downLoadManager = [LVDownLoadManager managerWithName:[NSString stringWithFormat:@"BNDOFFICDOC%@",[BNDPreference sharedInstance].openId]];
    LVDownLoadInfo *info = [_downLoadManager downloadInfoForURL:self.urlString];
    if(info == nil){
        info = [_downLoadManager creatDownloadTask:self.urlString name:_infoData[@"fileName"] progress:^(unsigned long long totalBytesWritten, unsigned long long totalBytesExpectedToWrite) {
             
          } state:^(LVDownloadState state, NSString *file, NSError *error) {
             
           
          }];
          
          [info setProgressChangeBlock:^(unsigned long long totalBytesWritten, unsigned long long totalBytesExpectedToWrite) {
              CGFloat  progressData  = ((float)totalBytesExpectedToWrite/totalBytesWritten);
              if (progressData > 0) {
                  BND_dispatch_main_async_safe(^{
                      [ReminderHUD showProgress:progressData status:@"下载中"];
                  })
              }
          }];
          @weakify(self)
          [info setStateChangeBlock:^(LVDownloadState state, NSString *file, NSError *error) {
              @strongify(self)
              if(state == LVDownloadStatedownLoadCompleted){
                  [ReminderHUD disappear];
                  [ReminderHUD showReminderText:@"下载成功" delayTime:1.0];
                  [self handleDocumentController:file and:self.infoData[@"fileName"]];
              }else{
                  [ReminderHUD showReminderText:@"下载失败" delayTime:1.0];
              }
          }];
    }else{
        [self handleDocumentController:info.downLoadingPath and:_infoData[@"fileName"]];
    }
 
}


- (void)handleDocumentController:(NSString *)fileURL and:(NSString*)fileName
{
    self.documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"file://\%@",fileURL]]];
    self.documentController.name = fileName;
    self.documentController.delegate = self;
    self.documentController.UTI = @"com.qqkj.mjpark";
//    self.documentController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.documentController presentOpenInMenuFromRect:CGRectZero  inView:[BNDPushVCHandler topViewController].view animated:YES];
}

#pragma mark --UIDocumentInteractionControllerDelegate--

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)interactionController
{
    return [BNDPushVCHandler topViewController];
}

-(UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
    return [BNDPushVCHandler topViewController].view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller
{
    return [BNDPushVCHandler topViewController].view.frame;
}

- (WKWebView *)webView
{
    if (!_webView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.allowsInlineMediaPlayback = YES;
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight) configuration:config];
        [_webView.scrollView setDelegate:self];
        [_webView setUIDelegate:self];
        [_webView setNavigationDelegate:self];
        //        [_webView setScalesPageToFit:YES];
        [_webView.scrollView setMinimumZoomScale:1.0f];
        [_webView.scrollView setMaximumZoomScale:1.0f];
        _webView.backgroundColor = [UIColor whiteColor];
        [_webView setOpaque:NO];
        if (@available(iOS 11.0, *)) {
            _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    
    return _webView;
}

// 页面准备加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"------页面准备加载时调用");
}
// 页面内容开始加载
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"------页面内容开始加载");
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"------页面,%@",error);
    //    if (error.code = 102) {
    //        [webView reload];
    //    }
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"------页面,%@",error);
}


// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
//    NSString *urlString = self.urlString;
//    NSData *data = [NSData dataWithContentsOfURL:navigationResponse.response.URL];
//    NSURL *weburl = [NSURL URLWithString:urlString];
//    [self.webView loadData:data MIMEType:@"application/pdf" characterEncodingName:@"UTF-8" baseURL:weburl];
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    
    if (navigationAction.navigationType == WKNavigationTypeReload) {
          decisionHandler(WKNavigationActionPolicyCancel);
      } else {
          decisionHandler(WKNavigationActionPolicyAllow);
      }
    //允许跳转
//    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //    decisionHandler(WKNavigationActionPolicyCancel);
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    // 禁用用户选择
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';"completionHandler:nil];
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
    
    if(self.isComplete == NO){
        _isComplete = YES;
        BND_BLOCK_EXEC(self.block,@"");
    }
}

- (void)loadDataMethod:(NSString*)url
{
   
    self.urlString = url;
    NSURL *weburl = [NSURL URLWithString:url];
    NSURLRequest *request;
    request = [NSURLRequest requestWithURL:weburl];
    [self.webView loadRequest:request];
}

- (void)reload
{
    [self loadDataMethod:self.urlString];
//    [self.webView reloadFromOrigin];
}
@end
